Skip to content

Studio images: batch MOSS-Image layer by layer so a streamed block uploads once per batch - #19957

Merged
danielhanchen merged 4 commits into
mainfrom
studio-batch-moss-layer-major
Nov 27, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-batch-moss-layer-major

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Studio images: MOSS-Image runs a streamed batch layer-major

Part of the image batching program (Phase 3 item 3). MOSS-Image was the one family that SGLang and vLLM-Omni batch while Studio did not really fuse it: MOSSImageTransformer.forward looped over the samples outside the layer loop. On a streamed (offloaded) DiT every block was uploaded once per row instead of once per batch, so a batch of 4 paid 4 full weight streams per step, and the batch matrix measured 1.00x.

What changes

  • Layer loop outer, rows inner. For a batch of 2 or more on an offloaded DiT, each _Block is called once with a tuple of rows, so its offload hook moves the block's weights once per call. Inside the block each row runs the unchanged solo computation at its own shape: its own text length, its own text refinement, its own mask slice and its own RoPE table. Nothing is padded and nothing is shared across rows except the uploaded weights.
  • AdaLN modulation at batch 1. The timestep MLP and the shared block / head modulation now run at batch 1 in this path (once for a shared timestep, once per row for per-row timesteps). The batch-B GEMM there was the only thing that made a batched row differ from its solo render (latent max abs up to 3.0 on main).
  • When it engages. Only when every block is reached through offload hooks that move weights and arguments only (diffusers group offload, its lazy-prefetch tracker, accelerate hooks). Resident weights, compiled blocks, CUDA-graph or cache wrappers, module forward hooks and gradient checkpointing keep main's per-sample forward. layer_major_stats() counts layer-major forwards, rows, and the per-sample fallbacks by reason.
  • Kill switch. UNSLOTH_MOSS_LAYER_MAJOR=0 restores main's order for every batch.
  • Admission. coalesce_prompt_key no longer refuses MOSS outright. It asks coalesce_key(pipe), which returns a key only for a load that runs layer-major on a card with a serving verdict in MEASURED_BATCH_WINS. Rows may differ in prompt length. The table holds one measured entry, NVIDIA A100-SXM4-80GB; every other card, and every resident or compiled load, keeps rendering concurrent MOSS requests one at a time.

G1, and why batch bytes change

  • A single-image request (N=1) is byte-identical to main, resident and streamed: N=1 never enters the new path.
  • A batch_size > 1 request on a streamed load now shares one layer-major pass, and its bytes change by design. On main each image of such a batch drifted from the image its own seed renders alone, because the modulation ran as one batch-B GEMM. Now each image is its own solo render bit for bit, so a returned seed replays exactly. That path is gated by G2a, G2c and the row-0 gate below instead of by byte equality with main.
  • Resident batches are unchanged from main (they keep the per-sample forward).

Gate table

One Colab A100-SXM4-80GB (torch 2.14.1, diffusers 0.42.1, transformers 5.15.1), weights unsloth/MOSS-Image-SFT-FP8 (bf16 transformer/, text_encoder/, vae/), SFT defaults, CFG 2.5, bf16 eager. Main and head ran in the same process on the same card, interleaved. Streamed = diffusers block-level group offload, one block per group, with streams. Gates at 512 px; speed at 1024 px, 10 steps, 3 ABBA repeats.

Gate Check Main Head Verdict
G1 N=1 latents, 4 prompts, resident and streamed sha256 equal to main, all 8 PASS
G1 resident N=2 / N=4 batch latents sha256 equal to main (per-sample kept) PASS
G1 streamed N=2 / N=4 batch latents differ from main by design (see above) by design
Row 0 batch rows vs their own solo renders, streamed max abs 2.75 (N=2 row 0), 2.92 (N=4 row 0) bit-identical, every row of N=2 and N=4 PASS
Row 0 same, resident max abs up to 3.01 same as main (per-sample kept) not promoted
G2a streamed batch of 4, neighbour prompt (other length) or seed changed, target first / middle / last, 6 cases target bit-identical in 6/6; rerun floor 0.0 PASS
G2c 8 held-out prompts x 3 seeds = 24 pairs, LPIPS(batched, fp32 ref) - LPIPS(solo, fp32 ref), streamed mean 0.0, 95% upper bound 0.0, worst pair 0.0; 24/24 batched latents equal their solos PASS
G3 block uploads per step at N=4, streamed 336 84 (kill switch: 336) PASS
G4 streamed N=1, head vs main 21.39 s 21.39 s (1.000x, CI 0.999-1.001) no regression
G4 streamed N=2, batched vs 2 serial 1.15x 1.98x (CI 1.98-1.99), p95 0.50x of serial PASS
G4 streamed N=4, batched vs 4 serial 1.26x 2.42x (CI 2.40-2.43), p95 0.41x of serial PASS
G4 resident N=2 / N=4, batched vs serial 0.997x 0.996x / 0.997x serial stays

Speedup CIs are t intervals on the log ratio over 3 paired repeats; p95 is the per-request completion latency. G2c uses the paired non-inferiority gate (larger of the t and bootstrap bounds, eps +0.01). Head N=4 streamed 35.5 s against main's 69.3 s for the same batch.

Tests

studio/backend/tests/test_diffusion_moss_layer_major.py (CPU, diffusers block-level group offload with both devices on the CPU, tiny random model):

  • batched rows equal their batch-1 forwards bit for bit (fp32 and bf16, ragged and equal lengths, refined text, per-row timesteps);
  • N=1 keeps the per-sample forward;
  • neighbour invariance with the target first, middle and last;
  • block uploads drop from 4 x layers to layers per call (kill switch restores the old count);
  • every fallback reason;
  • the pipeline with CFG, a per-row negative, an uncond skip layer and a seed list: each row is its own solo render;
  • coalescing waits for a serving verdict.

Against main's code 15 of 16 fail (the upload counter on its assertion, 16 vs 4). The MOSS, image concurrency and image batching suites pass (256 passed, 1 skipped).

Not proven

  • Compiled / CUDA-graphed streamed loads still run per-sample. This is the main follow-up: Auto compiles MOSS from the first render, so a default Auto load gains nothing yet. The compiled block's hooks run inside its compiled call. Calling that call once per row would re-upload per row, and bypassing the hooks would break the compiled guards and recompile on a request. It needs a separately compiled per-row block body warmed by the race.
  • Only diffusers block-level group offload was measured. Studio's own group prefetcher and packed group offload, hosted INT8 streaming and leaf-level offload were not run. Leaf-level offload gets no upload saving by construction.
  • Only an A100-SXM4-80GB was measured, so only that card serves batched. L4, T4, G4 (RTX PRO 6000), B200, AMD and Apple were not run.
  • INT8 ConvRot (the Auto default) was not measured; this run was bf16.
  • The real request route (coalescer, fair queue, account mixing) was not driven end to end. The gates call the pipeline directly with precomputed prompt embeddings.
  • G5 (OOM salvage at an admitted size) and G6 (fairness) were not measured here. The path keeps N rows' activations (about 25 MB each at 1024 px) alive at once instead of one.
  • Unrelated pre-existing behaviour seen on both arms: main's streamed and resident N=2 batch bytes differ from each other.

On an offloaded DiT a batch ran each row through all 42 blocks in turn, so a
streamed block uploaded once per row. The layer loop now runs outer and the
rows inner: each block is called once with every row, so its offload hook
moves the weights once per call, and inside the block each row runs the solo
computation at its own text length, mask and RoPE table. The AdaLN modulation
also runs at batch 1 (once for a shared timestep), so every row is its own
solo render bit for bit instead of carrying a batch-B GEMM's rounding. N=1
keeps the per-sample forward, and UNSLOTH_MOSS_LAYER_MAJOR=0 restores the old
order for every batch.

Resident, compiled, graphed or otherwise hooked blocks keep the per-sample
forward. Concurrent MOSS requests still render one at a time unless the card
has a measured verdict in MEASURED_BATCH_WINS (empty by default).
Measured on an A100-SXM4-80GB with the DiT streamed by block-level group
offload (bf16 eager, 1024 px, 10 steps, 3 ABBA repeats): one layer-major call
for N=2 runs 1.98x and for N=4 2.42x faster than N serial renders (95% CI
lower bounds 1.98x and 2.40x), with block uploads per step dropping from 336
to 84 at N=4. Every batched latent equals its own solo render (G2c n=24,
upper bound 0.0; row 0 identical at N=2 and N=4), so this card gets a serving
verdict. Resident loads measured 0.997x and keep rendering one at a time.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T12:19:11.052193Z fbd251c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-27T11:24:25.530147Z
We couldn’t complete this review. Comment @codex review to try again.
1d3aff3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1d3aff370e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

(Python 3.13, g-l) fails on this PR's change, not on main:

studio/backend/tests/test_image_concurrency_review.py::test_moss_image_never_batches
core/inference/diffusion.py:5130: in coalesce_prompt_key
    from .diffusion_moss_image import coalesce_key
core/inference/diffusion_moss_image.py:502: in <module>
    _ModelMixin, _ConfigMixin = _model_bases()
core/inference/diffusion_moss_image.py:497: in _model_bases
    from diffusers.configuration_utils import ConfigMixin
E   ModuleNotFoundError: No module named 'diffusers'

coalesce_prompt_key now imports diffusion_moss_image, and that module builds its model bases from diffusers at import time. The backend test shard has no diffusers, so the import fails. It would also fail in a Studio install without diffusers that only asks for a coalescing key. Moving coalesce_key (or whatever coalesce_prompt_key needs) somewhere that does not import diffusers at module load fixes it. So would deferring _model_bases() to first use.

…port

coalesce_prompt_key imported diffusion_moss_image (which needs diffusers at import) outside the
try, so a backend without diffusers raised from the key instead of rendering alone.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: fbd251cda8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit b78af6d into main Nov 27, 2026
1 check passed
@danielhanchen
danielhanchen deleted the studio-batch-moss-layer-major branch November 27, 2026 13:36
danielhanchen added a commit that referenced this pull request Nov 27, 2026
…ole CPU shard (15 reds on unrelated PRs) (#19974)

## Problem

`Repo tests (CPU, rest)` fails the same 15 tests on unrelated PRs (for
example #19518 and #19957). Every failure traces back to one test file
added in #19959, `tests/test_pp_native_fused_ce.py`:

1. **It sets `UNSLOTH_FORCE_CPU=1` at module level and never restores
it.** Collecting the file is enough. From then on, every test in that
pytest worker and every interpreter those tests spawn takes the CPU
route. That breaks tests that rely on the CUDA spoof or on the GPU
import path:
- `test_fp8_full_finetune_dequant.py`: the child goes down the CPU
loader, so no `FineGrainedFP8Config` is passed (`{'cls': 'NoneType',
'dequantize': None}`)
- `test_allow_cpu_import_driverless.py`: `import unsloth` with
`UNSLOTH_DISABLE_CPU_FALLBACK=1` now succeeds ("a device is visible;
this file proves nothing here")
- `test_lazy_openai_import_check.py`, `test_triton_optional_import.py`:
the child prints the CPU banner and the CPU-only warnings their output
checks do not expect
2. **Its own six tests fail even when run alone.** `build()` creates a
DeepSeek-V4.1 model from a config. With unsloth_zoo present, the engram
tables are parameter-free frozen tables that need a checkpoint, and none
is ever bound, so the forward raises `frozen table deepseek_v41 engram
layer 1 is not bound to its checkpoint`. The other DeepSeek-V4.1 tests
that build from a config (`test_deepseek_v41_native.py`,
`test_parallel_deepseek_v41_gloo.py`) call `set_engram_table` first.

Reproduced on main (`60248e78de`) with transformers 5.18.0, PEFT 0.22.0
and TRL 1.19.0, using both the released unsloth_zoo and zoo main:
- The four files together: 14 failed.
- `test_fp8_full_finetune_dequant.py` alone passes. With
`test_pp_native_fused_ce.py` only collected (not selected),
`test_lora_load_keeps_fp8` fails.

## Fix

- `tests/test_pp_native_fused_ce.py`:
- Sets `UNSLOTH_FORCE_CPU` only around the imports that need it
(unsloth_zoo, `pp_native`, the DeepSeek-V4.1 modules), then restores the
previous value.
- `build()` gives each engram table rows with `set_engram_table`, as the
other config-built DeepSeek-V4.1 tests do.
- `tests/conftest.py`, a guard against this kind of leak:
- A `pytest_make_collect_report` wrapper compares the device-route
variables after each test module is collected: `UNSLOTH_FORCE_CPU`,
`UNSLOTH_ALLOW_CPU`, `UNSLOTH_DISABLE_CPU_FALLBACK`,
`UNSLOTH_FORCE_GPU_PATH` and `CUDA_VISIBLE_DEVICES`.
- A module that leaves one changed fails its collection with a message
naming the module and the variable.
- The guard restores the variable, so the leak does not reach the rest
of the run.

## Verification

- `tests/test_pp_native_fused_ce.py`: 7 passed, with CUDA hidden and
with it visible. Before: 6 failed alone.
- The five affected files together, with CUDA hidden as on the CPU
runners: 18 passed, 9 skipped. Before: 14 failed.
- Collecting the whole `tests/` tree with the guard (`--collect-only`,
CUDA hidden): clean, no module trips it.
- Sabotage, with main's `test_pp_native_fused_ce.py` restored and the
guard kept: collection fails with `tests/test_pp_native_fused_ce.py
changed the device route for every later test while it was imported
(UNSLOTH_FORCE_CPU: None -> '1')`.
- `tests/python/test_conftest_bitsandbytes_preimport.py` and
`tests/python/test_accelerator_skip_guards.py`, which read the conftest:
passed.
danielhanchen added a commit that referenced this pull request Nov 27, 2026
…needs handles that can stay eager

The route's family check has no pipe, so for MOSS (which fuses rows only on
a measured layer-major load, decided from the pipe) it always refused, and
both image routes rendered MOSS one at a time despite #19957. The route now
refuses only when the answer cannot depend on the load and leaves MOSS to
coalesce_plan, which asks coalesce_key with the real pipe.

On handles that record graphs on demand (block graphs, no drop_batched) an
eager-arm win could not keep later coalesced calls eager: they would replay
graphs again while the verdict said eager. Such a win is now withheld, both
when the race decides and when a saved verdict is applied (including a
graphed win falling back to its eager arm).

[skip ci]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant